from django.contrib.auth.models import User

import current_user_middleware as threadlocals
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin.models import ADDITION,CHANGE,DELETION, LogEntry
from django.db import models
from django.db.models import signals
from django import forms
from django.db.models.base import ModelBase
import datetime
from django.core import serializers
from django.utils.translation import ugettext_lazy as _

ACTION_CHOICE = (
                 (ADDITION,"ADDITION"),
                 (CHANGE, "CHANGE"),
                 (DELETION, "DELETION")
                 )

class UpdatesHistory(models.Model):
    action_time = models.DateTimeField(_('date'), auto_now=True)
    user = models.ForeignKey(User, null=True, blank=True, default=None)
    content_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = models.IntegerField(_('object id'), blank=True, null=True)
    action_flag = models.PositiveSmallIntegerField(_('action flag'), choices=ACTION_CHOICE)
    changes = models.TextField(blank=True, null=True)

    def get_edited_object(self):
        "Returns the edited object represented by this log entry"
        return self.content_type.get_object_for_this_type(pk=self.object_id)
    
    target = property(get_edited_object)
         
    def target_url(self):
        "Returns the edited object link represented by this log entry"
        url = mark_safe(u"/admin/%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, quote(self.object_id)))
        obj= self.get_edited_object()
        #url = obj.get_admin_url()
        return "<a href=%s>%s</a>" % (url, obj.pk)

    target_url.allow_tags = True
    
    def __unicode__(self):
        return " %s " % get_choicename(self, "action_flag")[1]
    
    class Meta:
        app_label = 'xadmin'
        get_latest_by = "action_time"
    
    
